<template>
  <div>
    <el-card>
      <el-page-header icon="" content="添加产品" title="产品管理">
      </el-page-header>
      <el-form
        ref="productFormRef"
        :model="productForm"
        :rules="productFormRules"
        label-width="110px"
        class="demo-ruleForm"
      >
        <el-form-item label="产品名称" prop="title">
          <el-input v-model="productForm.title" />
        </el-form-item>
        <el-form-item label="产品简要描述" prop="introduction">
          <el-input v-model="productForm.introduction" type="textarea" />
        </el-form-item>
        <el-form-item label="产品详细描述" prop="detail">
          <el-input v-model="productForm.detail" type="textarea" />
        </el-form-item>

        <el-form-item label="产品图片" prop="cover">
          <Upload
            :avatar="productForm.cover"
            @fileChange="handleChange"
          ></Upload>
        </el-form-item>
        <el-form-item class="btn-right">
          <el-button type="primary" @click="submitForm()"> 提交 </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import Upload from '@/components/upload/Upload.vue'
import upload from '@/util/upload'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { ElMessage } from 'element-plus'
const store = useStore()

const router = useRouter()
const productFormRef = ref()
const productForm = reactive({
  title: '',
  detail: '',
  introduction: '',
  cover: '',
  creater: store.state.userInfo.userName,
  file: null
})
const productFormRules = reactive({
  title: [
    {
      required: true,
      // pattern: /0\d{2,3}-\d{7,8}/,
      message: '请输入用户名',
      trigger: 'blur'
    }
  ],
  detail: [{ required: true, message: '请输入产品详细描述', trigger: 'blur' }],
  introduction: [
    { required: true, message: '请输入产品简要描述', trigger: 'blur' }
  ],
  cover: [{ required: true, message: '请上传产品图片', trigger: 'blur' }]
})

const handleChange = (file) => {
  productForm.cover = URL.createObjectURL(file)
  // console.log(productForm.avatar)
  productForm.file = file
}

const submitForm = () => {
  productFormRef.value.validate(async (valid) => {
    if (valid) {
      // console.log('productForm', productForm)
      const res = await upload('/adminApi/product/add', productForm)
      // console.log(res.data);
      if (res.data.code == '0000') {
        ElMessage.success(res.data.msg)
        router.push(`/product-manage/ProductList`)
      }
    }
  })
}
</script>

<style scoped lang="scss">
.demo-ruleForm {
  margin-top: 50px;
}
.btn-right {
  float: right;
}
</style>
